package com.community.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.community.entity.Book;
import com.community.entity.Course;
import com.community.entity.CourseEnroll;
import com.community.entity.User;
import com.community.service.IBookService;
import com.community.service.ICourseEnrollService;
import com.community.service.ICourseService;

@Controller
@RequestMapping("/learn")
public class LearnCenterController {
	
	@Autowired
	private IBookService iBookService;
	@Autowired
	private ICourseService iCourseService;
	
	@Autowired
	private ICourseEnrollService iCourseEnrollService;
	
	@RequestMapping()
	public String learn_center(ModelMap modelMap){
		List<Book> bookList = iBookService.getBookLimitRand(4);
		List<Course> courseList= iCourseService.getCourseList(1);
		modelMap.addAttribute("bookList", bookList);
		modelMap.addAttribute("courseList", courseList);
		
		return "/learn/learn_center";
	}
	
	@RequestMapping("/detail/{id}")
	public String courseDetail(@PathVariable Long id,ModelMap modelMap){
		
		Course course = iCourseService.getCourseById(id);
		modelMap.addAttribute("course", course);
		return "/learn/course_detail";
		
	}
	
	@RequestMapping("/enroll")
	@ResponseBody
	public int courseEnroll(Long courseId,HttpSession session){
		
		if(session.getAttribute("userid") == null){
			return 0;
		}else{
			Long id = Long.valueOf(session.getAttribute("userid").toString());
			CourseEnroll ce= iCourseEnrollService.getCourseEnrollByUserIdAndCourseId(id, courseId);
			if(ce == null){
				CourseEnroll c = new CourseEnroll();
				c.setUserId(id);
				c.setCourseId(courseId);
				iCourseEnrollService.addCourseEnroll(c);
				return 1;
			}else{
				return 2;
			}
			
		}
		
	}
	
	@RequestMapping("/mycourse")
	public String myCourse(HttpSession session,ModelMap modelMap){
		if(session.getAttribute("userid") == null){
			return "/user/login";
		}else{
			Long id = Long.valueOf(session.getAttribute("userid").toString());
			List<CourseEnroll> CourseEnrollList= iCourseEnrollService.getCourseEnrollListByUserId(id);
			List<Course> courseList = new ArrayList<>();
			
			
			for (CourseEnroll courseEnroll : CourseEnrollList) {
				Course c = iCourseService.getCourseById(courseEnroll.getCourseId());
				courseList.add(c);
			}
			modelMap.addAttribute("courseList", courseList);
			return "/learn/my_course";
		
		}
		
	}

}
